//
//  WifiViewController.m
//  IPCamera
//
//  Created by 宣佚 on 15/6/29.
//  Copyright (c) 2015年 Andon Health Co,.Ltd. All rights reserved.
//

#import "WifiViewController.h"
#import "LPPopupListView.h"
#import "GCDAsyncSocket.h"

@interface WifiViewController () <LPPopupListViewDelegate,GCDAsyncSocketDelegate>

@property(nonatomic,strong)  GCDAsyncSocket *socket;

@property (nonatomic, strong) IBOutlet UITextField *ipField;
@property (nonatomic, strong) IBOutlet UITextField *portField;
@property (nonatomic, strong) IBOutlet UIButton *connectBut;

@property (nonatomic, strong) NSMutableIndexSet *selectedIndexes;
@property (nonatomic, strong) NSMutableArray *wifiList;
@property (nonatomic, strong) NSString *password;

@end

@implementation WifiViewController

@synthesize socket;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)connectButPress:(id)sender
{
    socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    //socket.delegate = self;
    NSError *err = nil;
    [MBProgressHUD showWaiting];
    if(![socket connectToHost:self.ipField.text onPort:[self.portField.text intValue] error:&err])
    {
        [MBProgressHUD showError:err.description];
    }else
    {
        NSLog(@"打开端口");
    }
}

-(IBAction)disconnectButPress:(id)sender
{
    [socket disconnect];
}

-(IBAction)setWifiButPress:(id)sender
{
    [self requestDevice];
}

#pragma mark - LPPopupListViewDelegate

- (void)popupListView:(LPPopupListView *)popUpListView didSelectIndex:(NSInteger)index
{
    NSLog(@"popUpListView - didSelectIndex: %ld", index);
}

- (void)popupListViewDidHide:(LPPopupListView *)popUpListView selectedIndexes:(NSIndexSet *)selectedIndexes
{
    NSLog(@"popupListViewDidHide - selectedIndexes: %@", selectedIndexes.description);
    
    self.selectedIndexes = [[NSMutableIndexSet alloc] initWithIndexSet:selectedIndexes];
}

#pragma mark - GCDAsyncSocketDelegate

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    [MBProgressHUD hideHUD];
    [MBProgressHUD showSuccess:[NSString stringWithFormat:@"连接到:%@",host]];
    [socket readDataWithTimeout:-1 tag:0];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    [MBProgressHUD showSuccess:@"断开连接"];
}

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
//    NSString *newMessage = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
//    [self addText:[NSString stringWithFormat:@"%@:%@",sock.connectedHost,newMessage]];
    [socket readDataWithTimeout:-1 tag:0];
}

#pragma mark - AP连AP流程

/**
 *  S1:手机发送连接请求给设备
 */
-(void)requestDevice
{
    [socket writeData:[@"REQ\r" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    [socket readDataWithTimeout:-1 tag:0];
}

/**
 *  S2:设备接收到请求后去搜索设备搜索范围内的所有WIFI
 *
 *  @param list 原始数据
 *
 *  @return 设备搜索范围内的所有WIFI
 */
-(NSMutableArray *)getWifiList:(NSMutableArray *)list
{
    self.wifiList = [[NSMutableArray alloc] initWithCapacity:1];
    [list enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        WifiListModel *model = [WifiListModel modelObjectWithDictionary:obj];
        [self.wifiList addObject:model];
    }];
    return self.wifiList;
}

/**
 *  手机接收到可连WIFI列表后选择一个WIFI
 *
 *  @param model WIFI信息
 */
-(void)requestselectOneWifi:(WifiListModel *)model
{
    NSMutableString *reqString = [[NSMutableString alloc] initWithString:@"RT+SET,"];
    NSArray *Security = [model.security componentsSeparatedByString:@"/"];
    [reqString appendString:[Security firstObject]];
    [reqString appendString:@","];
    [reqString appendString:[Security lastObject]];
    [reqString appendString:@","];
    [reqString appendString:model.sSID];
    [reqString appendString:@","];
    [reqString appendString:self.password];
    [reqString appendString:@","];
    [reqString appendString:model.ch];
    [reqString appendString:@","];
    [reqString appendString:@"\r"];
    [reqString appendString:@"\n"];
    [socket writeData:[reqString dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    [socket readDataWithTimeout:-1 tag:0];
}

/**
 *  确认连接
 */
-(void)confirmConnected
{
    [socket writeData:[@"SSID\r\n" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    [socket readDataWithTimeout:-1 tag:0];
}

@end
